
package com.j2eefast.bussiness.contract.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.j2eefast.bussiness.contract.entity.*;
import com.j2eefast.bussiness.contract.service.*;
import com.j2eefast.bussiness.contract.utils.MonthSheetWriteHandler;
import com.j2eefast.bussiness.contract.utils.ReadBusEquipmentExcelUtil;
import com.j2eefast.bussiness.contract.utils.ReadPatientExcelUtil;
import com.j2eefast.bussiness.contract.utils.StringUtils;
import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.*;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.framework.sys.entity.SysUserEntity;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.ueditor.define.ActionMap;
import com.j2eefast.framework.utils.Constant;
import com.j2eefast.framework.utils.Global;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>设备管理</p>
 *
 * @author: summer
 * @date: 2021-05-31 14:41
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */
@Controller
@RequestMapping("/bus/equipment")
public class BusEquipmentController extends BaseController {

	private String urlPrefix = "modules/bus/equipment";
	@Autowired
	private BusEquipmentService busEquipmentService;
	@Autowired
	private BusRepairService busRepairService;

	@Autowired
	private BusInstallsService busInstallsService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private BusClassifyService busClassifyService;

	@RequiresPermissions("bus:equipment:view")
	@GetMapping()
	public String process() {
		return urlPrefix + "/index";
	}

	@RequestMapping("/list")
	@RequiresPermissions("bus:equipment:list")
	@ResponseBody
	public ResponseData list(@RequestParam Map<String, Object> params) {
		String equipmentType = (String) params.get("equipmentType");
		PageUtil page = busEquipmentService.findPage(params);
		return success(page);
	}

	/**
	 * 删除
	 */
	@BussinessLog(title = "删除", businessType = BusinessType.DELETE)
	@RequestMapping( value = "/del", method = RequestMethod.POST)
	@RequiresPermissions("bus:equipment:del")
	@RequiresRoles(Constant.SU_ADMIN)
	@ResponseBody
	public ResponseData delete(Long[] ids) {
		return busEquipmentService.deleteByIds(ids)?success(): error("删除失败!");
	}

	/**
	 * 修改出入库 页面
	 */
	@RequiresPermissions("bus:equipment:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap) {
		BusEquipmentEntity busEquipmentEntity = busEquipmentService.getById(id);
		mmap.put("equipment", busEquipmentEntity);
//		List<BusInstallsEntity> busInstallsEntity=busInstallsService.getInstallsList();
////		Map<String, Object> list1 = new HashMap<String, Object>();
////		Map<String, Object> list2 = new HashMap<String, Object>();
////		Map<String, Object> list3 = new HashMap<String, Object>();
////		Map<String, Object> list4 = new HashMap<String, Object>();
////		Map<String, Object> list5 = new HashMap<String, Object>();
////		Map<String, Object> list6 = new HashMap<String, Object>();
//
//		List<BusInstallsEntity> list1=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list2=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list3=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list4=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list5=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list6=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list7=new ArrayList<BusInstallsEntity>();
//
//		for(int i=0;i<busInstallsEntity.size();i++){
//
//			switch ( busInstallsEntity.get(i).getType() ){
//				case 0:
//					list1.add(busInstallsEntity.get(i));
//					break;
//				case 1 :
//					list2.add(busInstallsEntity.get(i));
//					break;
//				case 2 :
//					list3.add(busInstallsEntity.get(i));
//					break;
//				case 3 :
//					list4.add(busInstallsEntity.get(i));
//					break;
//				case 4 :
//					list5.add(busInstallsEntity.get(i));
//					break;
//				case 5 :
//					list6.add(busInstallsEntity.get(i));
//					break;
//				case 6 :
//					list7.add(busInstallsEntity.get(i));
//					break;
//			}
//		}
//		mmap.put("meteringList",list1);
//		mmap.put("addrList",list2);
//		mmap.put("useList",list3);
//		mmap.put("safekeepingList",list4);
//		mmap.put("increaseList",list5);
//		mmap.put("usagesList",list6);
//		mmap.put("depreciationList",list7);
		this.info(mmap);
		return urlPrefix + "/edit";
	}

	/**
	 * 修改出入库保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:equipment:edit")
	@BussinessLog(title = "修改", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData edit(BusEquipmentEntity busEquipmentEntity) {
		ValidatorUtil.validateEntity(busEquipmentEntity);
		Date date = new Date();//创建一个时间对象，获取到当前的时间
		busEquipmentEntity.setUpdateTime(date);
//		Long userId= UserUtils.getUserInfo().getId();
//		SysUserEntity sysUserEntity=busEquipmentService.getSysById(userId);
//		busEquipmentEntity.setUpdateBy(sysUserEntity.getName());
		String userName=UserUtils.getUserInfo().getName();
		busEquipmentEntity.setCreateBy(userName);
		return busEquipmentService.updateById(busEquipmentEntity) ? success() : error("修改失败!");
	}

	/**
	 * 新增参数配置
	 */
	@RequiresPermissions("bus:equipment:add")
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		List<BusInstallsEntity> busInstallsEntity=busInstallsService.getInstallsList();
//		Map<String, Object> list1 = new HashMap<String, Object>();
//		Map<String, Object> list2 = new HashMap<String, Object>();
//		Map<String, Object> list3 = new HashMap<String, Object>();
//		Map<String, Object> list4 = new HashMap<String, Object>();
//		Map<String, Object> list5 = new HashMap<String, Object>();
//		Map<String, Object> list6 = new HashMap<String, Object>();

//		List<BusInstallsEntity> list1=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list2=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list3=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list4=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list5=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list6=new ArrayList<BusInstallsEntity>();
//		List<BusInstallsEntity> list7=new ArrayList<BusInstallsEntity>();
//
//		for(int i=0;i<busInstallsEntity.size();i++){
//
//			switch ( busInstallsEntity.get(i).getType() ){
//				case 0:
//					list1.add(busInstallsEntity.get(i));
//					break;
//				case 1 :
//					list2.add(busInstallsEntity.get(i));
//					break;
//				case 2 :
//					list3.add(busInstallsEntity.get(i));
//					break;
//				case 3 :
//					list4.add(busInstallsEntity.get(i));
//					break;
//				case 4 :
//					list5.add(busInstallsEntity.get(i));
//					break;
//				case 5 :
//					list6.add(busInstallsEntity.get(i));
//					break;
//				case 6 :
//					list7.add(busInstallsEntity.get(i));
//					break;
//			}
//		}
//		mmap.put("meteringList",list1);
//		mmap.put("addrList",list2);
//		mmap.put("useList",list3);
//		mmap.put("safekeepingList",list4);
//		mmap.put("increaseList",list5);
//		mmap.put("usagesList",list6);
//		mmap.put("depreciationList",list7);
		this.info(mmap);
		return urlPrefix + "/add";
	}

	public ModelMap info(ModelMap mmap){
		//List<BusInstallsEntity> busInstallsEntity=busInstallsService.getInstallsList();
		List<BusClassifyEntity> busClassifyEntity=busClassifyService.getInstallsList();
		List<BusClassifyEntity> list1=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list2=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list3=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list4=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list5=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list6=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list7=new ArrayList<BusClassifyEntity>();
		List<BusClassifyEntity> list8=new ArrayList<BusClassifyEntity>();
		for(int i=0;i<busClassifyEntity.size();i++){

			if(busClassifyEntity.get(i).getParentId()!=null){
				switch(busClassifyEntity.get(i).getParentId().intValue() ){
					case 1:
						System.out.println("2222");
						System.out.println(busClassifyEntity.get(i));
						System.out.println("11112222111111");
						list1.add(busClassifyEntity.get(i));
						break;
					case 2 :
						list2.add(busClassifyEntity.get(i));
						break;
					case 3 :
						list3.add(busClassifyEntity.get(i));
						break;
					case 4 :
						list4.add(busClassifyEntity.get(i));
						break;
					case 5 :
						list5.add(busClassifyEntity.get(i));
						break;
					case 6 :
						list6.add(busClassifyEntity.get(i));
						break;
					case 7 :
						list7.add(busClassifyEntity.get(i));
						break;
					case 8 :
						list8.add(busClassifyEntity.get(i));
						break;
				}
			}
		}
		mmap.put("equipmentList",list1);//设备分类
		mmap.put("meteringList",list2);//计量单位
		mmap.put("addrList",list3);//存放地点
		mmap.put("useList",list4);//使用部门
		mmap.put("safekeepingList",list5);//保管人员
		mmap.put("increaseList",list6);//增加方式
		mmap.put("usagesList",list7);//使用情况
		mmap.put("depreciationList",list8);//折旧方法
		return mmap;
	}
	/**
	 * 新增保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:equipment:add")
	@BussinessLog(title = "认领", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData addSave(@Validated BusEquipmentEntity busEquipmentEntity) {
		//校验参数
		ValidatorUtil.validateEntity(busEquipmentEntity);

		return busEquipmentService.saves(busEquipmentEntity) ? success() : error("新增失败!");
	}

	/**
	 * 修改出入库保存
	 */
	@RequiresPermissions("bus:equipment:checkout")
	@BussinessLog(title = "出库", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/checkout", method = RequestMethod.POST)
	@ResponseBody
//	@GetMapping("/checkout/{id}")
	public ResponseData checkout(String id, ModelMap mmap) {
		System.out.println("1111111111111111111111");
		ValidatorUtil.validateEntity(id);
		Long ids=Long.parseLong(id);
		return busEquipmentService.updateCheck(ids) ? success() : error("修改失败!");
	}


	/**
	 * 修改出入库 页面
	 */
	@RequiresPermissions("bus:equipment:repair")
	@GetMapping("/repair/{id}")
	public String repair(@PathVariable("id") int id, ModelMap mmap) {
		List<BusRepairEntity> busRepairEntity = busRepairService.repairList(id);
		mmap.put("repair", busRepairEntity);
		mmap.put("equipment",id);
		return urlPrefix + "/edit1";
	}

	/**
	 * 修改修改认领保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:equipment:repair")
	@BussinessLog(title = "维修记录", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/repair", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData repair(HttpServletRequest request, Model model) throws ParseException {

		return busRepairService.repairSave(request,model) ? success() : error("修改失败!");
	}

	@BussinessLog(title = "导出", businessType = BusinessType.EXPORT)
	@RequiresPermissions("bpm:equipment:export")
	@PostMapping("/export")
	@ResponseBody
	public ResponseData export(@RequestParam Map<String, Object> params) throws Exception {
		WriteCellStyle headWriteCellStyle = new WriteCellStyle();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
		String date = sdf.format(new Date());
		String fileName =  "设备信息";
//		// 表头
//		List<List<String>> heads = new ArrayList<List<String>>();
//		StringBuffer sb = new StringBuffer("三联单库查询：");
//		sb.append("表单名："+fileName + "操作时间:"+ date);
		fileName = ToolUtil.encodingExcelFilename(fileName);
		String folder = Global.getTempPath() + File.separator + "pio" + File.separator;
//		FileUtil.touch(folder + fileName);
		List<BusEquipmentEntity> listData = busEquipmentService.findList(params);
//		List pilebodysList = pilebodycheckService.pilebodystatisticsmonth(sysDepartDto, month);
//设置序号
//		for (int i = 1; i <= listData.size(); i++) {
//			listData.get(i - 1).setOrderNum(i + "");
//		}
//		response.setContentType("application / vnd.ms - excel");
//		response.setCharacterEncoding("utf - 8");
//// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//		String fileName = URLEncoder.encode("存量建筑垃圾堆体治理进度月报表", "UTF - 8");
//		response.setHeader("Content - disposition", "attachment; filename ="+fileName + ".xls");
//内容样式策略
		WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
		contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
		contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
		contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
		contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
		contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置 自动换行
		contentWriteCellStyle.setWrapped(true);
// 字体策略
		WriteFont contentWriteFont = new WriteFont();
// 字体大小
		contentWriteFont.setFontHeightInPoints((short) 12);
		contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认


		//excel如需下载到本地,只需要将response.getOutputStream()换成File即可(注释掉以上response代码)
		EasyExcel.write(folder + fileName, BusEquipmentEntity.class)
				//设置输出excel版本,不设置默认为xlsx
				.excelType(ExcelTypeEnum.XLS).head(BusEquipmentEntity.class)
				//设置拦截器或自定义样式
//				.registerWriteHandler(new MonthSheetWriteHandler())
//				.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
				.sheet("设备信息")
				//设置默认样式及写入头信息开始的行数
				.useDefaultStyle(true).relativeHeadRowIndex(3)
				//这里的addsumColomn方法是个添加合计的方法,可删除
				.doWrite(listData);

		return success(fileName);
	}



	/**
	 * 上传excel
	 */
	@BussinessLog(title = "上传文件", businessType = BusinessType.UPDATE)
	@PostMapping("/upload")
	@RequiresPermissions("bpm:equipment:upload")
	@RepeatSubmit
	@ResponseBody
	public ResponseData upload(@RequestParam("files") MultipartFile file){
		try{
			if (!file.isEmpty()){
				String pathName = FileUploadUtil.uploadFile(Global.getTempPath(), file);
				int rowSuccess=0;		//标记成功导入的数据条数
				List<BusEquipmentEntity> excelInfo = ReadBusEquipmentExcelUtil.getExcelInfo(file,pathName);		//调用工具类，传入excel文件，得到数组对象
				for (BusEquipmentEntity patientInfo : excelInfo) {
					int patientCount =busEquipmentService.getEquipmentInfo(patientInfo.getEquipmentCode());
					if (patientCount>0){//如果大于零表示已存在
						//sanLianService.updateByIds(patientInfo);
					}else {
						boolean save = busEquipmentService.save(patientInfo);
						//如果不存在，将数据道存到数据库
						if (save){
							rowSuccess++;		//保存成功后，成功数+1
						}
					}
				}
				return success();
			}
			return error(ToolUtil.message("sys.file.null"));
		}
		catch (Exception e)
		{
			System.out.println(e);
			return error("c出错误了"+e);
		}
	}



}
